<?php

namespace app\admin\controller\basic;

use app\common\controller\Backend;
use think\Db;
use fast\Random;

/**
 * 学段列表
 */
class Studylevel extends Backend
{

    /**
     * @var \app\common\model\Studylevel
     */
    protected $model = null;
  
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Studylevel;
        $schoolList = Db::name("school")->select();
        // 如果查询结果为空，赋值为空数组
        $this->schoolList = is_array($schoolList)? $schoolList : [];
        $schooldata = [0 => __('None')];
        foreach ($this->schoolList as $k => &$v) {
            $schooldata[$v['id']] = $v['name'];
        }
        $this->view->assign('schooldata', $schooldata);
    }

    /**
     * 查看
     */
    public function index(){
        if ($this->request->isAjax()) {

            // 获取请求参数
            $params = $this->request->param();

            // 查询数据（带分页）
            $list = $this->model
                ->with('school')
                ->order($params['sort'] ?? 'id', $params['order'] ?? 'desc')
                ->paginate([
                    'list_rows' => $params['limit'] ?? 10,
                    'page'      => ($params['offset'] / $params['limit'] + 1) ?? 1
                ]);
            // 返回标准JSON格式
            $result = [
                "total" => $list->total(),
                "rows"  => $list->items()
            ];
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post('row/a');
            if (empty($data['level_name']) || empty($data['school_id'])) {
                $this->error('参数不能为空');
            }
            $schoolId = isset($data['school_id'])? $data['school_id'] : [];
            unset($data['school_id']);
            Db::startTrans();
            try {
                $result = $this->model->save($data);
                if ($result === false) {
                    $this->error('添加失败');
                }
                $studyIevelId = $this->model->id;
                if (!empty($schoolId)) {
                    $schoolData = [
                        'school_id' => $schoolId,
                        'study_level_id' => $studyIevelId,
                    ]; 
                    $schoolModel = Db::name('school_study_level_relation');
                    $schoolModel->insert($schoolData);
                }
                Db::commit();
            }catch (\Exception $e) {
                Db::rollback();
                $this->error('添加失败: '. $e->getMessage());
            }
        } 
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
       if($this->request->isPost()) {
            $data = $this->request->post('row/a');
            $row = $this->model->get($ids);
            $school_id = isset($data['school_id']) ? $data['school_id'] : [];
            unset($data['school_id']);
            Db::startTrans();
            try {
                $result = $row->save($data);
                if ($result === false) {
                    $this->error('更新失败');
                }
                if (!empty($ids)) {
                    if(!empty($school_id)){
                        $schoolData = [
                           'school_id' => $school_id,
                           'study_level_id' => $ids,
                        ];
                        $schoolModel = Db::name('school_study_level_relation');
                        $schoolModel->where('study_level_id', $ids)->delete();
                        $schoolModel->insert($schoolData);
                    }else{
                        $this->error('请选择学校');
                    }
                }
                Db::commit();
            }catch (\Exception $e) {
                Db::rollback();
                $this->error('更新失败: '. $e->getMessage());
            };
       }
       $row = $this->model->get($ids);
       if (!$row) {
           $this->error(__('未找到该数据'));
       }
       $relatedSchool = Db::name('school_study_level_relation')
            ->where('study_level_id', $ids)
            ->column('school_id');
        $this->view->assign([
            'row' => $row,
            'relatedSchool' => $relatedSchool,
        ]);
       return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = null)
    {
        if ($ids) {
            $rows = $this->model->where('id', 'in', $ids)->delete();
            if ($rows) {
                Db::name('school_study_level_relation')->where('study_level_id', 'in', $ids)->delete();
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
        $this->error('请选择要删除的记录');
    }
}